package cn.pconline.autoclub.web;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Activity;
import cn.pconline.autoclub.entity.Album;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubDyna;
import cn.pconline.autoclub.entity.ClubForum;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.DynaPraise;
import cn.pconline.autoclub.entity.DynaReply;
import cn.pconline.autoclub.entity.Subject;
import cn.pconline.autoclub.entity.SubjectDyna;
import cn.pconline.autoclub.entity.Topic;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.entity.UserDyna;
import cn.pconline.autoclub.entity.UserVoted;
import cn.pconline.autoclub.entity.Vote;
import cn.pconline.autoclub.entity.VoteDetail;
import cn.pconline.autoclub.service.ActivityService;
import cn.pconline.autoclub.service.AlbumService;
import cn.pconline.autoclub.service.CensorDynaInfoService;
import cn.pconline.autoclub.service.CensorDynaReplyService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.DynaIndexService;
import cn.pconline.autoclub.service.EffectiveDynaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.SubjectDynaService;
import cn.pconline.autoclub.service.SubjectService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.service.VoteService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.Bread;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.StringUtil;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.dyna.CommentDyna;
import cn.pconline.autoclub.util.dyna.CommentDynaUtils;
import cn.pconline.officialclub.entity.OActivity;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.service.OActivityService;
import cn.pconline.officialclub.service.OClubService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.danga.MemCached.MemCachedClient;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.gelivable.dao.GeliDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author <a href="mailto:chensy0203@163.com">chensy</a>
 */
@Controller
@RequestMapping("/dyna")
public class DynaController {

    @Autowired
    private EffectiveDynaService dynaService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private GeliDao geliDao;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private CensorDynaInfoService censorDynaInfoService;
    @Autowired
    private AlbumService albumService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private CensorDynaReplyService censorDynaReplyService;
    @Autowired
    private MemCachedClient mcc;
    @Autowired
    private VoteService voteService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private SubjectDynaService subjectDynaService;
    @Autowired
    private OActivityService oActivityService;
    @Autowired
    private OClubService oClubService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private DynaIndexService dynaIndexService;
    
    private static final Logger log = LoggerFactory.getLogger(DynaController.class);
    private static final int DEFAULT_PAGE_SIZE = 20;//默认分页大小
    private static final int DEFAULT_PRAISE_PAGE_SIZE = 13;//动态详细页点赞用户分页大小 获取点赞用户第一页列表,一页最多13个，页面要求
    private static final int MAX_PAGE_SIZE = 100;
    private static final int MIN_PAGESIZE = 1;
    private static final int DEFAULT_AUTHORPHOTO_SIZE = 50;//作者头像50X50
    public static final int DEFAULT_MAX_IMAGE_SIZE = 9;//发表动态超多9张图片
    public static final int DEFAULT_MAX_CONTENT_LENGTH = 300;//动态内容最大长度为300
    private static final int DEFAULT_MAX_REPLY_LENGTH = 150;//回复内容最大长度为150
    private static final String DEFAULT_USERNAME = "游客";
    private static final int MAX_TOP_COUNT = 5;//最大置顶数

    private void printMsg(HttpServletResponse resp, String str, String callback) {
        callback = EncodeUtils.encodeForHTMLFilterNull(callback);
        try {
            java.io.PrintWriter w = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                w.print(callback + "(" + str + ")");
            } else {
                w.print(str);
            }
            w.flush();
            w.close();
        } catch (IOException ex) {
            log.error("response输出出错了", ex);
        }
    }

    private void printSuccessMsg(HttpServletResponse resp, String msg, JSONObject data, String callback) {
        JSONObject json = new JSONObject();
        json.put("code", AppUtils.STATUS_OK);
        if (StringUtils.isNotEmpty(msg)) {
            json.put("message", msg);
        }
        if (data != null) {
            json.put("data", data);
        }
        printMsg(resp, json.toJSONString(), callback);
    }

    private void printErrorMsg(HttpServletResponse resp, int code, String msg, String callback) {
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("message", msg);
        printMsg(resp, json.toJSONString(), callback);
    }

    private void printErrorMsg(HttpServletResponse resp, String msg, String callback) {
        printErrorMsg(resp, AppUtils.STATUS_FAIL, msg, callback);
    }

    private String redirect404(HttpServletResponse response) {
        try {
            response.sendError(404);
        } catch (Exception ex) {
            log.error("redirect404 fial!", ex);
        }
        return "/template/common/notFoundPage";
    }

    /**
     * 帖子列表页
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/list.do", method = RequestMethod.GET)
    public String list(HttpServletRequest request, HttpServletResponse response) {
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", Topic.TYPE_TOPIC_PAGESIZE, 1, MAX_PAGE_SIZE);
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        int order = WebUtils.paramInt(request, "order", 0);

        Club club = clubService.getValidClub(clubId);
        if (club == null || pageNo < 1) {
            try {
                response.sendError(404);
                return null;
            } catch (Exception ex) {
                log.error("list topics fail!", ex);
            }
            return "/template/common/notFoundPage";
        }
        User user = userAuth.getUser(request, response);
        boolean isOwner = false;
        boolean isClubUser = false;
        ClubMember clubMember = memberService.findMember(user.getUid(), clubId);
        if (clubMember != null && clubMember.getId() > 0) {
            isClubUser = true;
        }
        if (clubMember != null && clubMember.isAdmin()) {
            isOwner = true;
        }
        Pager<DynaInfo> pager;
        pager = dynaService.getTopicDynaListByClubId(clubId, pageNo, pageSize, order);
        //过滤掉不合法的图片
        pager = dynaService.filterImages(pager);
        if (pager == null) {
            pager = Pager.buildEmptyPager();
        }
        List<ClubForum> clubForums = clubService.getForumList(club.getClubId());
        WebUtils.checkPageMaxNo(response, pageNo, pager.getPageCount());
        ClubController.setClubStyle(request, club.getClubId());
        request.setAttribute("clubForums", clubForums);
        request.setAttribute("isOwner", isOwner);
        request.setAttribute("isClubUser", isClubUser);
        request.setAttribute("order", order);
        request.setAttribute("clubId", clubId);
        request.setAttribute("pager", pager);
        request.setAttribute("user", userAuth.getUser(request, response));
        request.setAttribute("club", club);
        return "/template/dyna/list";
    }

    /**
     * 车友会动态接口 请求参数： clubId:车友会ID（二选一） userId:用户Id（二选一） TODO 迟点考虑下拆成两个接口
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/getDynaList", method = RequestMethod.GET)
    @ResponseBody
    public void getDynaList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        long userId = WebUtils.paramLong(request, "userId", 0L);
        int type = WebUtils.paramInt(request, "type", 0);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEFAULT_PAGE_SIZE, MIN_PAGESIZE, MAX_PAGE_SIZE);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int sourceAgent = WebUtils.paramInt(request, "source_agent", 1);

        //获取配置文件中的动态切图参数
        int imageQua = systemConfig.getImageQua();
        //判断参数是否合法
        if (clubId == 0L && userId == 0L) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法参数clubId|userId", callback);
            return;
        }
        if (clubId > 0L && userId > 0L) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法参数clubId|userId", callback);
            return;
        }
        JSONObject json = new JSONObject();
        boolean isUserId = false;//车友会ID，用户ID，二选一
        JSONArray jsonArray = new JSONArray();
        Pager<DynaInfo> pager = null;
        //根据userId分页查找动态列表
        if (userId > 0L) {
            if (type == 0) {//获取所有动态信息
                pager = dynaService.getDynaListByUserId(userId, null, pageNo, pageSize);
            } else if (type == 1) {//获取帖子信息
                pager = dynaService.getDynaListByUserId(userId, null, pageNo, pageSize, DynaInfo.getTopicType());
            } else if (type == 2) {//获取留言信息
                pager = dynaService.getDynaListByUserId(userId, null, pageNo, pageSize, DynaInfo.TYPE_COMMENT);
            } else {
                printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法参数type", callback);
                return;
            }
            isUserId = true;
        }
        //根据clubId分页查找动态列表
        if (clubId > 0L) {
            if (type == 0) {//获取所有动态信息
                pager = dynaService.getDynaListByClubId(clubId, pageNo, pageSize);
            } else if (type == 1) {//获取帖子信息
                pager = dynaService.getDynaListByClubId(clubId, pageNo, pageSize, DynaInfo.getTopicType());
            } else if (type == 2) {//获取留言信息
                pager = dynaService.getDynaListByClubId(clubId, pageNo, pageSize, DynaInfo.TYPE_COMMENT);
            } else {
                printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法参数type", callback);
                return;
            }
        }
        if (pager == null && pageNo == 1) {
            printErrorMsg(response, "没有相关的动态信息！", callback);
            return;
        }
        if (pager != null) {
            WebUtils.checkPageMaxNo(response, pageNo, pager.getPageCount());
            for (DynaInfo dynaInfo : pager.getResultList()) {
                JSONObject jsonObject = dynaService.toJson4Pc(dynaInfo, sourceAgent, imageQua);
                jsonObject.put("createAt", DateUtils.formatYYMMDDHM(dynaInfo.getCreateDate()));
                jsonArray.add(jsonObject);
            }
            if (isUserId) {// 车友会ID，用户ID，二选一
                json.put("userId", userId);
            } else {
                json.put("clubId", clubId);
            }
            json.put("data", jsonArray);
            json.put("total", pager.getTotal());
            json.put("pageNo", pager.getPageNo());
            json.put("pageSize", pager.getPageSize());
            json.put("code", AppUtils.STATUS_OK);
            json.put("message", "成功获取车友会动态列表！");
            printMsg(response, json.toString(), callback);
        }
    }

    /**
     * 组装动态Json
     *
     * @param dynaInfo
     * @param sourceAgent
     * @param imageQua
     * @return
     */
    public JSONObject setJson4DynaInfo(DynaInfo dynaInfo, int sourceAgent, int imageQua) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("postCount", dynaInfo.getPostCount());
        jsonObject.put("pubTime", dynaInfo.getCreateDate());
        jsonObject.put("topicTitle", dynaInfo.getTitle() == null ? "" : dynaInfo.getTitle());
        jsonObject.put("forumName", dynaInfo.getForumName() == null ? "" : dynaInfo.getForumName());
        jsonObject.put("isPick", (dynaInfo.getPick() == 1 || dynaInfo.getPick() == 2));
        jsonObject.put("isPost", (dynaInfo.isTopic()));
        jsonObject.put("authorId", dynaInfo.getCreateBy());
        jsonObject.put("forumId", dynaInfo.getForumId());
        // 根据UserID获取昵称、头像
        User user = userService.findUser(dynaInfo.getCreateBy());
        jsonObject.put("authorName", user == null ? dynaInfo.getCreateName() : user.getUsername());
        String nickName = dynaInfo.getCreateName();
        if (user != null) {
            nickName = user.getNickname() == null ? user.getUsername() : user.getNickname();
        }
        jsonObject.put("nickname", nickName);
        jsonObject.put(
                "authorPhoto",
                user == null ? WebUtils.face(0,
                DEFAULT_AUTHORPHOTO_SIZE) : WebUtils.face(
                user.getUid(), DEFAULT_AUTHORPHOTO_SIZE));

        jsonObject.put("contribution", dynaInfo.getPetrol());
        jsonObject.put("topicId", dynaInfo.getTopicId());
        jsonObject.put("isRecommend", (dynaInfo.getRecommend() == 1));
        jsonObject.put("content", WebUtils.transformNoBBSFaceThenLimit(dynaInfo.getContent(), 300, sourceAgent));
        jsonObject.put("dynaInfoId", dynaInfo.getDynaInfoId());
        jsonObject.put("type", dynaInfo.getType());

        JSONArray images = new JSONArray();
        List<DynaImage> dynaImages = dynaInfo.getImages();
        int imgCount = dynaImages.size();
        for (DynaImage dynaImage : dynaImages) {// 获取图片列表信息(URL,width,height必须有值
            if (StringUtils.isBlank(dynaImage.getUrl())) {
                continue;
            }
            /*无宽高，多图时也出; 无宽高单张图时不出*/
            if (imgCount == 1 && dynaImage.getWidth() == 0 && dynaImage.getHeight() == 0) {
                break;
            }
            JSONObject o = new JSONObject();
            o.put("seq", dynaImage.getSeq());
            o.put("url", dynaImage.getUrl500x500());
            o.put("width", dynaImage.getWidth());
            o.put("height", dynaImage.getHeight());
            o.put("qua", imageQua);
            images.add(o);
        }
        jsonObject.put("images", images);

        return jsonObject;
    }

    /**
     * 列表页的下动态的回复列表
     *
     * @param request
     * @param response
     * @return 返回html片段
     */
    @RequestMapping(value = "/getReplyListPage")
    public String getReplyListPage(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        User user = userAuth.getUser(request, response);
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        if (0 == clubId || dynaInfoId == 0) {
            return redirect404(response);
        }
        ClubDyna clubDyna = dynaService.findClubDynaById(dynaInfoId, clubId);
        if (clubDyna == null || clubDyna.getStatus() == ClubDyna.STATUS_DELETE) {
            return redirect404(response);
        }
        String page = WebUtils.param(request, "page", "index");
        DynaInfo dynaInfo = dynaService.findDynaInfoById(dynaInfoId, clubDyna.getCreateDate());
        Pager<DynaReply> pager = dynaService.getReplyListByDynaInfoId(dynaInfoId, 1, 10);
        String clubUrl = clubService.getClub(clubId).getClubUrl();
        request.setAttribute("pager", pager);
        request.setAttribute("postCount", dynaInfo.getPostCount());
        request.setAttribute("page", page);
        request.setAttribute("dynaInfo", dynaInfo);
        request.setAttribute("clubUrl", clubUrl);
        request.setAttribute("user", user);
        return "template/dyna/replyList";
    }

    /**
     * 动态回复列表接口 请求参数：dynaInfoId
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getReplyList", method = RequestMethod.GET)
    @ResponseBody
    public void getReplyList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEFAULT_PAGE_SIZE, 1, MAX_PAGE_SIZE);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int source_agent = WebUtils.paramInt(request, "source_agent", 2);
        int descType = WebUtils.paramInt(request, "descType", 1);//0：顺序，1：倒序
        if (dynaInfoId == 0) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "请输入合法的dynaInfoId", callback);
            return;
        }
        Pager<DynaReply> pager = dynaService.getReplyListByDynaInfoId(dynaInfoId, descType, pageNo, pageSize);
        JSONObject obj = null;
        if (pager != null) {
            WebUtils.checkPageMaxNo(response, pageNo, pager.getPageCount());

            JSONArray arr = new JSONArray();
            for (DynaReply info : pager.getResultList()) {
                //根据UserID获取昵称、头像
                User user = userService.findUser(info.getCreateBy());//回复用户
                User postToUser = userService.findUser(info.getPostToUserId());//被回复用户
                JSONObject object = info.getJSONObject(source_agent);
                object.put("authorPhoto", WebUtils.face(info.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
                object.put("nickname", user == null ? DEFAULT_USERNAME : user.getNickname());
                object.put("postToNickName", postToUser == null ? DEFAULT_USERNAME : postToUser.getNickname());
                SimpleDateFormat sdf = new SimpleDateFormat("MM:dd HH:mm:ss");
                object.put("showDate", sdf.format(info.getCreateDate()));
                arr.add(object);
            }
            obj = pager.toJSONObject(arr);
        }
        obj.put("dynaInfoId", dynaInfoId);

        obj.put("code", AppUtils.STATUS_OK);
        obj.put("message", "成功获取车友会回复列表！");
        printMsg(response, obj.toString(), callback);
    }

    /**
     * 获取单条动态详情 请求参数：dynaInfoId clubId
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/dynaDetail", method = RequestMethod.GET)
    public String dynaDetail(HttpServletRequest request, HttpServletResponse response) {
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEFAULT_PAGE_SIZE, 1, MAX_PAGE_SIZE);
        long clubId = WebUtils.paramLong(request, "clubId", 0);

        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            return redirect404(response);
        }
        if (pageNo < 1 || 0 == clubId || dynaInfoId == 0) {
            return redirect404(response);
        }
        ClubDyna clubDyna = dynaService.findClubDynaById(dynaInfoId, clubId);
        //判断动态是否存在、是否为帖子（包含提问）、是否为删除动态
        if (clubDyna == null || DynaInfo.isTopic(clubDyna.getType())
                || clubDyna.getStatus() == ClubDyna.STATUS_DELETE) {
            //帖子动态没有详情页
            return redirect404(response);
        }
        DynaInfo dynaInfo = dynaService.findDynaById(dynaInfoId, clubDyna.getCreateDate());
        if (dynaInfo == null) {
            log.error("车友会动态索引表有脏数据[clubId,dynaInfoId][{},{}]，对应的动态不存在", clubId, dynaInfoId);
            return redirect404(response);
        }
        dynaService.filterImages(dynaInfo);//过滤掉不合法的图片
        String content = dynaInfo.getContent();
        User user = userAuth.getUser(request, response);
        String shareContent = dynaInfo.getContent();
        if (dynaInfo.getType() == DynaInfo.TYPE_ACTIVITY) {
            Activity a = activityService.findById(dynaInfo.getTargetId());
            if (a == null) {
                log.error("dirty data,targetId not correct :[dynaInfo:{}],[clubId:{}],[targetId(activityId):{}]", dynaInfo.getDynaInfoId(), dynaInfo.getClubId(), dynaInfo.getTargetId());
                return redirect404(response);
            }
            content = a.getTitle();//活动动态的content没存
            shareContent = a.getTitle();
            request.setAttribute("activity", a);
        } else if (dynaInfo.getType() == DynaInfo.TYPE_PICTURE) {
            Album a = albumService.getAlbumById(dynaInfo.getTargetId());
            if (a == null) {
                log.error("dirty data,targetId not correct :[dynaInfo:{}],[clubId:{}],[targetId(albumId):{}]", dynaInfo.getDynaInfoId(), dynaInfo.getClubId(), dynaInfo.getTargetId());
                return redirect404(response);
            }
            request.setAttribute("album", a);
            request.setAttribute("pictureNum", dynaInfo.getPictureNum());
            content = a.getName();//相片动态的content存的是图片数量
            String nickName = EncodeUtils.encodeForHTML(userService.findUser(dynaInfo.getCreateBy()).getNickname());
            shareContent = nickName + "上传了" + dynaInfo.getPictureNum() + "张相片到 《" + a.getName() + "》";
        } else if (dynaInfo.getType() == DynaInfo.TYPE_CREATE_CLUB) {
            content = club.getName();
            shareContent = "我创建了" + club.getName() + "车友会，大家都赶紧邀请车友加入吧，多人才好玩哦！";
        } else if (dynaInfo.getType() == DynaInfo.TYPE_JOIN_CLUB) {
            content = club.getName();
            shareContent = "Hello，我已经加入了<a href=\"" + systemConfig.getRoot() + "/" + club.getClubUrl() + "/\" target=\"_blank\">" + club.getName() + "</a>，现在我是一个有组织的人了，欢迎大家来围观！";
        } else if (dynaInfo.getType() == DynaInfo.TYPE_COMMENT) {
            if (!StringUtils.isBlank(dynaInfo.getSubjectIds())) {
                request.setAttribute("isSubject", true);
            }
        } else if (dynaInfo.getType() == DynaInfo.TYPE_NOTICE) {
            request.setAttribute("noticeId", dynaInfo.getClubId());
        } else if (dynaInfo.getType() == DynaInfo.TYPE_QUESTION || dynaInfo.getType() == DynaInfo.TYPE_TOPIC) {
            request.setAttribute("topicId", dynaInfo.getTargetId());
            shareContent = dynaInfo.getTitle();
        } else if (dynaInfo.getType() == DynaInfo.TYPE_VOTE) {
            //投票对象
            Vote vote = voteService.findVoteByVoteId(dynaInfo.getTargetId());
            long voteId = vote == null ? 0 : vote.getVoteId();
            //投票选项列表
            List<VoteDetail> voteDetails = new ArrayList<VoteDetail>();
            if (vote != null) {
                voteDetails = voteService.listDetailsByVoteId(voteId);
            }
            //是否已经投票
            long userId = user.getUid();
            UserVoted userVote = voteService.findVoteByUserId(voteId, userId);
            boolean isVoteCreator = false;	//是否为投票发起人
            if (userId == vote.getCreateBy()) {
                isVoteCreator = true;
            }
            request.setAttribute("isVoteCreator", isVoteCreator);
            request.setAttribute("isVoted", userVote != null);
            request.setAttribute("vote", vote);
            request.setAttribute("voteDetails", voteDetails);
        }
        dynaInfo.setCreateName(userService.findUser(dynaInfo.getCreateBy()).getNickname());
        request.setAttribute("club", club);
        request.setAttribute("dynaInfo", dynaInfo);
        request.setAttribute("content", content);
        //用户相关
        boolean isClubAdmin = false;
        boolean isPresident = false;
        boolean isMember = false;
        boolean isOwner = false; //判断是否是创建者
        if (user.getUid() != 0L) {
            ClubMember member = memberService.findMember(user.getUid(), clubId);
            if (member != null) {
                isClubAdmin = member.isAdministrator();
                isPresident = member.isAdmin();
                isMember = true;
            }
            if (dynaInfo.getCreateBy() == user.getUid()) {
                isOwner = true;
            }
        }

        String sharePic = "";  //分享的图片
        if (dynaInfo.getImages().size() >= 1) {
            sharePic = dynaInfo.getImages().get(0).toString();
        }
        request.setAttribute("user", user);
        request.setAttribute("isMember", isMember);
        request.setAttribute("isLogin", user.getUid() > 0);
        request.setAttribute("isPresident", isPresident);
        request.setAttribute("isClubAdmin", isClubAdmin);
        request.setAttribute("isOwner", isOwner);
        request.setAttribute("shareContent", shareContent);
        request.setAttribute("sharePic", sharePic);
        //回复列表
        Pager<DynaReply> pager = dynaService.getReplyListByDynaInfoId(dynaInfoId, pageNo, pageSize);
        WebUtils.checkPageMaxNo(response, pageNo, pager.getPageCount());
        request.setAttribute("pager", pager);
        Pager<User> praisePager = dynaService.getPraiseUserList(dynaInfoId, 1, DEFAULT_PRAISE_PAGE_SIZE);
        request.setAttribute("praisePager", praisePager);
        int praseCount = dynaService.getPraseCountByUid(dynaInfoId, user.getUid());
        if (praseCount == 1) {
            request.setAttribute("isPraise", true);
        } else {
            request.setAttribute("isPraise", false);
        }
        //seo要求
        String dynaDescForTitle = StringUtil.byteSubstring(content, 30, null);
        String dynaDescForDesc = StringUtil.simpleStringFilter(content, "img");//过滤图片
        dynaDescForDesc = dynaDescForDesc.replaceAll("\\[em([0-9]*)\\]", "[图]");//过滤表情
        dynaDescForDesc = StringUtil.byteSubstring(dynaDescForDesc, 112, "。。。。。。");//截取前100个汉字+6个省略号
        request.setAttribute("dynaDescForTitle", dynaDescForTitle);
        request.setAttribute("dynaDescForDesc", dynaDescForDesc);
        //自定义样式
        ClubController.setClubStyle(request, clubId);
        return "template/dyna/detail";
    }

    /**
     * 获取单条动态详情的所有图片 请求参数：dynaInfoId 提供给大图展示用的
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getDynaImages", method = RequestMethod.GET)
    @ResponseBody
    public void getDynaImages(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        long createBy = WebUtils.paramLong(request, "createBy", 0);

        //先从车友会分表查找是否存在，如果不存在再从用户分表进行查找，防止话题页面图片看不到
        ClubDyna clubDyna = dynaService.findClubDynaById(dynaInfoId, clubId);
        UserDyna userDyna;
        DynaInfo info;
        if (clubDyna == null || clubDyna.getStatus() == ClubDyna.STATUS_DELETE) {
            userDyna = dynaService.findUserDynaById(dynaInfoId, createBy);
            if (userDyna == null || userDyna.getStatus() == UserDyna.STATUS_DELETE) {
                printMsg(response, "[]", callback);
                return;
            }
            info = dynaService.findDynaInfoById(dynaInfoId, userDyna.getCreateDate());
        } else {
            info = dynaService.findDynaInfoById(dynaInfoId, clubDyna.getCreateDate());
        }

        if (info == null) {
            printMsg(response, "[]", callback);
            return;
        }

        info.setImages(dynaService.getImagesByDynaInfoId(dynaInfoId, 0));//查所有图片
        dynaService.filterImages(info);

        JSONArray arr = new JSONArray();
        for (DynaImage image : info.getImages()) {
            arr.add(image.toJSONObject());
        }
        printMsg(response, arr.toJSONString(), callback);
    }

    /**
     * 获取单条动态详情 请求参数：dynaInfoId clubId
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getDynaDetail", method = RequestMethod.GET)
    @ResponseBody
    public void getDynaDetail(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        Date createDate = WebUtils.parseDate(request, "createDate", null);
        int sourceAgent = WebUtils.paramInt(request, "source_agent", 1);

        //获取配置文件中的动态切图参数
        int imageQua = systemConfig.getImageQua();

        if (dynaInfoId == 0 || createDate == null) {
            printErrorMsg(response, "请输入合法的参数：dynaInfoId,createDate", callback);
            return;
        }
        DynaInfo info = dynaService.findDynaById(dynaInfoId, createDate);
        if (info == null) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "动态不存在！", callback);
        } else {
            //增加作者头像
            //JSONObject jsonObject = info.toJSONObject();
            //jsonObject.put("authorPhoto", info.getCreateBy() == 0L ? "" : WebUtils.face(info.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
            JSONObject jsonObject = setJson4DynaInfo(info, sourceAgent, imageQua);
            printSuccessMsg(response, "", jsonObject, callback);
        }
    }

    /**
     * 添加留言的接口
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/createCommentDyna", method = RequestMethod.POST)
    @ResponseBody
    public void createCommentDyna(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        String content = WebUtils.param(request, "content", "");
        String images = WebUtils.param(request, "images", "");
        long provinceId = WebUtils.paramLong(request, "provinceId", 0L);
        long cityId = WebUtils.paramLong(request, "cityId", 0L);
        int fromType = WebUtils.paramInt(request, "fromType",DynaInfo.FROM_APP);
        JSONObject successObject = new JSONObject(); //成功发表的动态
        JSONArray successImgs = new JSONArray();//成功发表的动态图片
        /*等待车友会页面发动态修改传provinceId时，才放开此条件
         if(provinceId == 0) {
         printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法参数：provinceId", callback);
         return;
         }
         */
        if (StringUtils.length(content) > DEFAULT_MAX_CONTENT_LENGTH) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法参数：content的最大长度为" + DEFAULT_MAX_CONTENT_LENGTH, callback);
            return;
        }
        JSONArray jsonArray = null;
        JSONObject json = new JSONObject();
        if (StringUtils.isNotBlank(images)) {

            try {
                jsonArray = JSONArray.parseArray(images);
            } catch (JSONException ex) {
                AppUtils.setDataErrorCode(json, "参数images的Json格式不正确！");
                printMsg(response, json.toString(), callback);
                return;
            }
        }
        if (StringUtils.isNotBlank(content) || (jsonArray != null && jsonArray.size() > 0)) {
            User user = userAuth.getUser(request, response);//验证用户是否登录
            if (user == null || user.getUid() == 0L) {
                printErrorMsg(response, AppUtils.STATUS_NOLOGIN_ERROR, "您还没有登录", callback);
                return;
            }
            long clubId = 0;
            ClubMember m = memberService.findClubMemberByUserId(user.getUid());
            if (m != null) {//当前登录用户的userId
                clubId = m.getClubId();
            }

            /*
             //判断重复提交
             StringBuilder keyBuilder = new StringBuilder();
             keyBuilder.append("Dyna-Repeat-Post-").append(user.getUid());
             keyBuilder.append("-").append(clubId);
             keyBuilder.append("-").append(content.hashCode());
             keyBuilder.append("-").append(images.hashCode());
             try {
             if (mcc.get(keyBuilder.toString()) != null) {
             printErrorMsg(response, "重复提交！", callback);
             return;
             }
             } catch (Exception e) {
             log.error("check repeat post error: {}", e.getMessage());
             }
             */

            // 增加留言
            CommentDyna commentDyna = new CommentDyna();
            commentDyna.setClubId(clubId);
            commentDyna.setCreateBy(user.getUid());
            commentDyna.setCreateDate(new Date());
            commentDyna.setCreateName(user.getNickname() != null ? user.getNickname() : user.getUsername());
            commentDyna.setContent(content);
            commentDyna.setUpdateDate(new Date());
            commentDyna.setProvinceId(provinceId);
            commentDyna.setCityId(cityId);
            commentDyna.setFromType(fromType);
            // 增加留言图片
            List<DynaImage> dynaImages = new ArrayList<DynaImage>();
            // 最多只可以上传9张图片
            if (jsonArray != null) {
                if (jsonArray.size() > DEFAULT_MAX_IMAGE_SIZE) {
                    json.put("code", AppUtils.STATUS_DATA_ERROR);
                    json.put("message", "发表动态最多可以上传" + DEFAULT_MAX_IMAGE_SIZE
                            + "张图片!");
                    printMsg(response, json.toString(), callback);
                    return;
                }
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject o = JSONObject.parseObject(jsonArray.getString(i));
                    DynaImage dynaImage = new DynaImage();
                    dynaImage.setSeq(i + 1);// 车友会的图片的seq跟论坛的图片的seq都统一从1开始
                    dynaImage.setUrl(o.getString("url"));
                    dynaImage.setWidth(NumberUtils.toInt(o.getString("width")));
                    dynaImage.setHeight(NumberUtils.toInt(o.getString("height")));
                    dynaImages.add(dynaImage);
                    //（用于首页js刷新）
                    JSONObject d = dynaImage.toJSONObject();
                    String url;
                    if (jsonArray.size() > 1) {
                        url = dynaImage.getUrl120x80();
                    } else {
                        url = (dynaImage.getUrl240x160());
                    }
                    d.put("url", url);
                    successImgs.add(d);
                }
            }


            // 图片的URL不可以为空
            for (DynaImage dynaImage : dynaImages) {
                String url = dynaImage.getUrl();
                if (StringUtils.isBlank(url)) {// 注意：这里限制了只有合法的图片才能上传
                    json.put("code", AppUtils.STATUS_DATA_ERROR);
                    json.put("message", "图片的URL不可以为空!");
                    printMsg(response, json.toString(), callback);
                    return;
                }
            }

            // 保存留言、图片
            DynaInfo dynaInfo = dynaService.createCommentDyna(commentDyna, dynaImages);
            if (dynaInfo.getDynaInfoId() == 0L) {
                printErrorMsg(response, "操作失败！", callback);
            } else {
                // 动态送审
                censorDynaInfoService.notifyCensorSystemCreate(request, commentDyna, dynaInfo.getDynaInfoId());
                //组装成功发表后对象（用于首页js刷新）
                int needToViewUrl = WebUtils.paramInt(request, "needToViewUrl", 0);
                if (needToViewUrl == 1) {
                    successObject.put("content", WebUtils.dynaSubjectContent(systemConfig.getRoot(), WebUtils.transformToBBSFace(CommentDynaUtils.appendUrlUBB(commentDyna.getContent())), dynaInfo.getSubjectIds()));
                } else {
                    successObject.put("content", WebUtils.dynaSubjectContent(systemConfig.getRoot(), WebUtils.transformToBBSFace(commentDyna.getContent()), dynaInfo.getSubjectIds()));
                }
                successObject.put("type", DynaInfo.TYPE_COMMENT);

                //区分是不是话题动态
                if (!StringUtils.isBlank(dynaInfo.getSubjectIds())) {
                    successObject.put("templateId", "template-subjectDyna");
                    successObject.put("subjectCount", subjectDynaService.countSubjectDyna(dynaInfo.getSubjectIds()));
                } else {
                    successObject.put("templateId", "template-commentDyna");
                }
                successObject.put("avatar", WebUtils.face(commentDyna.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
                successObject.put("nickName", userService.findUser(commentDyna.getCreateBy()).getNickname());
                successObject.put("userId", commentDyna.getCreateBy());
                successObject.put("dynaInfoId", dynaInfo.getDynaInfoId());
                successObject.put("year", DateUtils.format(commentDyna.getCreateDate(), "yyyy"));
                successObject.put("createDate", DateUtils.format(commentDyna.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                successObject.put("fmtCreateDate", DateUtils.format(commentDyna.getCreateDate(), "MM-dd HH:mm:ss"));
                successObject.put("praiseCount", 0);	//	刚发表点赞数默认为0
                successObject.put("postCount", 0);		//  刚发表回复数默认为0
                successObject.put("images", successImgs);

                printSuccessMsg(response, "操作成功！", successObject, callback);
                /*
                 try {
                 mcc.set(keyBuilder.toString(), "1", org.apache.commons.lang.time.DateUtils.addMinutes(new Date(), 1));
                 } catch (Exception e) {
                 log.error("check repeat post error: {}", e.getMessage());
                 }
                 */
            }
        } else {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "内容不能为空", callback);
        }
    }

    /**
     * 添加回复的接口，回复的回复的接口 如果参数replyDynaReplyId > 0, 表示是回复的回复 如果参数replyDynaReplyId
     * = 0，且dynaInfoId和createDate是有效的，才是动态的直接回复
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/replyDyna.do", method = RequestMethod.POST)
    public void replyDyna(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long postToDynaReplyId = WebUtils.paramLong(request, "postToDynaReplyId", 0L);
        int source_agent = WebUtils.paramInt(request, "source_agent", 2);
        String content = WebUtils.param(request, "content", "");
        Date createDate = WebUtils.parseDate(request, "createDate");
        if (createDate == null || dynaInfoId == 0 || StringUtils.isBlank(content)) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法参数createDate|dynaInfoId|content", callback);
            return;
        }
        //判断被回复的ID是否存在
        if (postToDynaReplyId > 0L) {
            DynaReply dynaReply = dynaService.findDynaReplyById(postToDynaReplyId, dynaInfoId);
            if (dynaReply == null) {
                printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法参数dynaInfoId|postToDynaReplyId", callback);
                return;
            }
        }

        if (StringUtils.length(content) > DEFAULT_MAX_REPLY_LENGTH) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "回复内容不能超过" + DEFAULT_MAX_REPLY_LENGTH + "个字符", callback);
            return;
        }
        JSONObject json = new JSONObject();
        User user = userAuth.getUser(request, response);//验证用户是否登录
        if (user == null || user.getUid() == 0) {
            printErrorMsg(response, AppUtils.STATUS_NOLOGIN_ERROR, "您还没有登陆", callback);
            return;
        }
        //      ClubMember clubMember = memberService.findMember(user.getUid(), clubId);//验证是否为车友会成员
        DynaInfo dynaInfo = dynaService.findDynaById(dynaInfoId, createDate);//判断动态ID是否正确
        if (dynaInfo == null && postToDynaReplyId == 0L) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "动态ID或者创建时间参数无效!");
            printMsg(response, json.toString(), callback);
            return;
        }

        DynaReply reply = new DynaReply();
        reply.setContent(content);
        reply.setCreateBy(user.getUid());
        reply.setCreateName(user.getNickname() == null ? user.getUsername() : user.getNickname());
        reply.setDynaInfoId(dynaInfoId);
        reply.setCreateAt(new Date());
        reply.setUpdateAt(new Date());
        reply.setPostToDynaReplyId(postToDynaReplyId);
        if (postToDynaReplyId > 0) {
            DynaReply dynaReply = dynaService.findDynaReplyById(postToDynaReplyId, dynaInfoId);
            if (dynaReply == null) {
                printErrorMsg(response, "回复ID有误！", callback);
                return;
            }
            reply.setPostToUserId(dynaReply.getCreateBy());
            reply.setPostToNickName(dynaReply.getCreateName());
        }
        long update = dynaService.replyCommentDyna(reply);
        if (update == 0) {
            printErrorMsg(response, "操作失败！", callback);
        } else {
            if (!StringUtils.isBlank(dynaInfo.getSubjectIds())) {   //如果该动态属于某一个话题.(话题动态回复数+1)
                List<Long> list = dynaInfo.getSubjectList();
                for (long sId : list) {
                    SubjectDyna subjectDyna = subjectDynaService.findSubjectDynaById(sId, dynaInfoId);
	                if(subjectDyna.getStatus() == SubjectDyna.STATUS_NORMAL){
	                    int count = subjectDyna.getPostCount() + 1;
	                    subjectDyna.setPostCount(count);
	                    subjectDynaService.updateByField(subjectDyna, "post_count");
	                    
	                    //回复话题动态时候，相应的话题回复数+1
	                    Subject subject = subjectService.findSubjectById(sId);
	                    if(subject !=null){
	                    	long sujectReplyCount = subject.getReplyCount() + 1;
	                    	subject.setReplyCount(sujectReplyCount);
	                    	subjectService.updateByField(subject, "reply_count");
	                    }
                    }
                }
            }
            //返回操作成功的数据信息，用户APP刷新页面显示
            dynaService.updateLastReplyInfo(dynaInfoId, 0L, createDate,
                    reply.getCreateBy(), reply.getCreateName(), reply.getCreateDate());
            reply.setDynaReplyId(update);
            JSONObject obj = reply.getJSONObject(source_agent);
            obj.put("postToUserName", reply.getPostToNickName() == null ? "" : reply.getPostToNickName());
            obj.put("myIcon", WebUtils.face(reply.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
            obj.put("time", DateUtils.format(reply.getCreateAt(), "MM-dd HH:mm"));
            obj.put("showCreateDate", DateUtils.format(reply.getCreateAt(), "yyyy-MM-dd"));
            obj.put("showContent", WebUtils.transformToBBSFace(reply.getContent()));
            obj.put("replyId", update);//返回给APP接口
            obj.put("authorPhoto", WebUtils.face(user.getUid(), DEFAULT_AUTHORPHOTO_SIZE));//返回给APP接口
            obj.put("nickname", user.getNickname() == null ? "" : user.getNickname()); //返回给APP接口
            obj.put("postToNickName", reply.getPostToNickName() == null ? "" : reply.getPostToNickName()); //返回给APP接口
            //发送审核平台
            Club club = clubService.getClub(dynaInfo.getClubId());
            if (club != null) {
                try {
                    censorDynaReplyService.notifyCensorSystemCreate(request, reply, dynaInfo);
                } catch (Exception e) {
                    log.error("send to conser error:{}", e.getMessage());
                }
            }
            printSuccessMsg(response, "操作成功！", obj, callback);
            //收到的回复发送
            //品牌车友会的活动动态屏蔽
            if (dynaInfo.getType() != DynaInfo.TYPE_JOIN_ACTIVITY) {
                dynaService.setJson4BipToListReply(reply, createDate);
            }
        }
    }

    /**
     * 审核查看动态页面
     *
     * @param req
     * @param resp
     *
     * @return
     */
    @RequestMapping(value = "/getDynaInfoDetail", method = RequestMethod.GET)
    public String getDynaInfo(HttpServletRequest req, HttpServletResponse resp) {
        long dynaInfoId = WebUtils.paramLong(req, "dynaInfoId", 0);
        String dateStr = WebUtils.param(req, "createDate", "");
        long replyId = WebUtils.paramLong(req, "dynaReplyId", 0);
        if (dynaInfoId == 0 && replyId == 0) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("getDynaInfo fail--sendError!", ex);
            }
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date date;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException ex) {
            date = new Date();
            log.error("getDynaInfo fail--ParseException!", ex);
        }
        if (dynaInfoId > 0) {
            DynaInfo dynaInfo = dynaService.findDynaById(dynaInfoId, date);
            if (dynaInfo == null || dynaInfo.getCensored() == DynaInfo.CENSORED_NOTPASS) {
                try {
                    resp.sendError(404);
                } catch (IOException ex) {
                    log.error("getDynaInfo fail--findDynaById!", ex);
                }
                return null;
            }
            DynaReply dynaReply = dynaService.findDynaReplyById(replyId, dynaInfoId);
            if(dynaReply!=null && dynaReply.getStatus()==DynaReply.STATUS_NORMAL){
                req.setAttribute("dynaReply", dynaReply);
            }
            req.setAttribute("dynaInfo", dynaInfo);
        }
        return "template/dyna/dynaInfo";
    }

    /**
     * 获取同城动态列表(APP接口）
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/listLocalDyna.do", method = RequestMethod.GET)
    public void listLocalDyna(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        long provinceId = WebUtils.paramLong(request, "provinceId", 0L);
        long cityId = WebUtils.paramLong(request, "cityId", 0L);
        int pageSize = WebUtils.paramInt(request, "pageSize", 20);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int total = 0;
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        //provinceId为必传参数
        if (provinceId == 0L) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "非法参数provinceId！");
            printMsg(response, json.toString(), callback);
            return;
        }
        Pager<DynaInfo> pager = dynaService.getDynaListByCityId(provinceId, cityId, pageNo, pageSize);
        if (pager != null) {
            total = pager.getTotal();
            for (DynaInfo dynaInfo : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("postCount", dynaInfo.getPostCount());//回复数
                jsonObject.put("pubTime", dynaInfo.getCreateDate());//发布时间
                jsonObject.put("authorId", dynaInfo.getCreateBy());//作者ID,
                jsonObject.put("forumId", dynaInfo.getForumId());//版块ID
                User user = userService.findUser(dynaInfo.getCreateBy());
                jsonObject.put("authorName", user == null ? dynaInfo.getCreateName() : user.getUsername());//作者名称
                String nickName = dynaInfo.getCreateName();
                if (user != null) {
                    nickName = user.getNickname() == null ? user.getUsername() : user.getNickname();
                }
                jsonObject.put("nickname", nickName);//作者昵称
                jsonObject.put("contribution", dynaInfo.getPetrol());//油值
                jsonObject.put("dynaInfoId", dynaInfo.getDynaInfoId());//动态ID
                jsonObject.put("authorPhoto", user == null ? WebUtils.face(0,
                        DEFAULT_AUTHORPHOTO_SIZE) : WebUtils.face(
                        user.getUid(), DEFAULT_AUTHORPHOTO_SIZE));//用户头像
                jsonObject.put("isRecommend", dynaInfo.getRecommend());//是否推荐
                jsonObject.put("content", dynaInfo.getContent());//动态内容
                List<DynaImage> images = dynaInfo.getImages();
                if (images != null && !images.isEmpty()) {
                    JSONArray array = new JSONArray();
                    for (DynaImage img : images) {
                        array.add(img.toJSONObject());
                    }
                    jsonObject.put("images", array);
                }
                jsonArray.add(jsonObject);
            }
        }
        json.put("data", jsonArray);
        json.put("total", total);
        json.put("pageNo", pageNo);
        json.put("pageSize", pageSize);
        json.put("code", AppUtils.STATUS_OK);
        json.put("message", "成功获取同城动态列表！");
        printMsg(response, json.toString(), callback);
    }

    /**
     * 获取同城动态列表(WAP同城首页的同城动态列表显示，与APP接口分开）
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/listLocalDynaWap.do", method = RequestMethod.GET)
    public void listLocalDynaWap(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        long provinceId = WebUtils.paramLong(request, "provinceId", 0L);
        long cityId = WebUtils.paramLong(request, "cityId", 0L);
        int pageSize = WebUtils.paramInt(request, "pageSize", 20);
        int isTranceFace = WebUtils.paramInt(request, "isTranceFace", 0);
        int source_agent = WebUtils.paramInt(request, "source_agent", 2);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int total = 0;
        JSONArray jsonArray = new JSONArray();
        JSONObject json = new JSONObject();
        //provinceId为必传参数
        if (provinceId == 0L) {
            json.put("code", AppUtils.STATUS_DATA_ERROR);
            json.put("message", "非法参数provinceId！");
            printMsg(response, json.toString(), callback);
            return;
        }
        //只显示动态，不包括帖子
        Pager<DynaInfo> pager = dynaService.getCommentDynaListByCityId(provinceId, cityId, pageNo, pageSize);
        if (pager != null) {
            total = pager.getTotal();
            for (DynaInfo dynaInfo : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("postCount", dynaInfo.getPostCount());//回复数
                Date pubTime = dynaInfo.getCreateAt();
                if (pubTime == null) {
                    pubTime = dynaInfo.getCreateDate();
                }
                jsonObject.put("pubTime", pubTime);//发布时间,时间戳
                jsonObject.put("pubTimeYmd", DateUtils.formatYYMMDDHM(pubTime));//发布时间,yyyy-MM-dd HH:mm
                jsonObject.put("authorId", dynaInfo.getCreateBy());//作者ID,
                jsonObject.put("forumId", dynaInfo.getForumId());//版块ID
                User user = userService.findUser(dynaInfo.getCreateBy());
                jsonObject.put("authorName", user == null ? dynaInfo.getCreateName() : user.getUsername());//作者名称
                String nickName = dynaInfo.getCreateName();
                if (user != null) {
                    nickName = user.getNickname() == null ? user.getUsername() : user.getNickname();
                }
                jsonObject.put("nickname", nickName);//作者昵称
                jsonObject.put("contribution", dynaInfo.getPetrol());//油值
                jsonObject.put("dynaInfoId", dynaInfo.getDynaInfoId());//动态ID
                jsonObject.put("authorPhoto", user == null ? WebUtils.face(0,
                        DEFAULT_AUTHORPHOTO_SIZE) : WebUtils.face(
                        user.getUid(), DEFAULT_AUTHORPHOTO_SIZE));//用户头像
                jsonObject.put("isRecommend", dynaInfo.getRecommend());//是否推荐
                jsonObject.put("type", dynaInfo.getType());
                //设置动态内容，帖子显示标题，动态显示内容
                String content = EncodeUtils.encodeForHTML(dynaInfo.getContent(), source_agent);
                jsonObject.put("content", isTranceFace == 0 ? WebUtils.transformToBBSFace(content) : content);
                jsonObject.put("desUrl", systemConfig.getWapRoot() + "/dt/" + dynaInfo.getDynaInfoId() + "/" + provinceId + "/" + cityId);
                String postTime = DateUtils.getFormatedTime(dynaInfo.getLastPostAt());
                if (postTime == null) {
                    postTime = DateUtils.getFormatedTime(pubTime);
                }
                jsonObject.put("postTime", postTime);//时间（格式为多少分钟之前发表）
                JSONArray images = new JSONArray();
                List<DynaImage> list = dynaInfo.getImages();
                if (list != null && list.size() > 0) {
                    int len = list.size();
                    for (DynaImage image : list) {
                        JSONObject imgObj = new JSONObject();
                        if (len <= DEFAULT_MAX_IMAGE_SIZE && len > 1) {
                            imgObj.put("width", 74);
                            imgObj.put("height", 74);
                            imgObj.put("smaPic", WebUtils.transPicUrl(image.getUrl500x500(), 150, 150));
                            imgObj.put("bigPic", image.getUrl400x400());
                        } else {
                            float width = image.getWidth();
                            float height = image.getHeight();
                            if (width > height) {
                                if (height < 90) {
                                    if (width > 300) {
                                        height = 90;
                                        width = 300;
                                    } else {
                                        height = height / (width / 300);
                                        width = 300;
                                    }
                                } else {
                                    height = height / (width / 300);
                                    width = 300;
                                }
                            } else if (height > width) {
                                if (width < 90) {
                                    if (height > 300) {
                                        height = 90;
                                        width = 300;
                                    } else {
                                        width = width / (height / 300);
                                        height = 300;
                                    }
                                } else {
                                    width = width / (height / 300);
                                    height = 300;
                                }
                            } else if (width == height) {
                                height = 300;
                                width = 300;
                            }
                            imgObj.put("width", (int) width / 2);
                            imgObj.put("height", (int) height / 2);
                            imgObj.put("smaPic", WebUtils.transPicUrl(image.getUrl500x500(), (int) width, (int) height));
                            imgObj.put("bigPic", image.getUrl400x400());
                        }
                        images.add(imgObj);
                    }
                }
                jsonObject.put("piclist", images);
                jsonArray.add(jsonObject);
            }
        }
        json.put("data", jsonArray);
        json.put("total", total);
        json.put("pageNo", pageNo);
        json.put("pageCount", pager == null ? 0 : pager.getPageCount());
        json.put("pageSize", pageSize);
        json.put("code", AppUtils.STATUS_OK);
        json.put("message", "成功获取同城动态列表！");
        printMsg(response, json.toString(), callback);
    }

    /**
     * 给个人中心查看看车友会动态的统一入口
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index(HttpServletRequest request, HttpServletResponse response) {
        User user = userAuth.getUser(request, response);
        if (user.getUid() > 0) {
            ClubMember m = memberService.findClubMemberByUserId(user.getUid());
            if (m != null) {
                Club club = clubService.getClub(m.getClubId());
                return "redirect:" + systemConfig.getRoot() + "/" + club.getClubUrl() + "/";
            }
        }
        return "redirect:" + systemConfig.getRoot() + "/";
    }

    @ResponseBody
    @RequestMapping(value = "/getTopList.do", method = RequestMethod.GET)
    public void getTopList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = null;
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        Club club = clubService.getValidClub(clubId);
        if (clubId == 0 || club == null) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法请求参数", callback);
            return;
        }
        Pager<DynaInfo> pager = dynaService.getTopDynaListByClubId(clubId, MAX_TOP_COUNT);
        JSONArray arr = new JSONArray();
        if (pager != null) {
            List<DynaInfo> list = pager.getResultList();
            for (DynaInfo i : list) {
                JSONObject obj = new JSONObject();
                String t = i.getTitle() == null ? "" : i.getTitle().trim();
                if (i.getType() == DynaInfo.TYPE_ACTIVITY) {
                    Activity a = activityService.findById(i.getTargetId());
                    if (a == null) {
                        log.error("maybe dirty data!!activity[{}] not exist![dynaInfoId:{},createAt:{},clubId:{}]", i.getTargetId(), i.getDynaInfoId(), i.getCreateBy(), i.getClubId());
                        continue;
                    }
                    t = a.getTitle();
                } else if (i.getType() == DynaInfo.TYPE_JOIN_ACTIVITY) {
                    OActivity a = oActivityService.findValidActivity(i.getTargetId());
                    if (a == null) {
                        log.error("maybe dirty data!!oActivity[{}] not exist![dynaInfoId:{},createAt:{},clubId:{}]", i.getTargetId(), i.getDynaInfoId(), i.getCreateBy(), i.getClubId());
                        continue;
                    }
                    OClub oClub = oClubService.findValidClub(a.getOClubId());
                    if (oClub == null) {
                        log.error("oClub! dirty data,oClubId not correct :[dynaInfo:{}],[clubId:{}],[oClubId:{}]", i.getDynaInfoId(), i.getClubId(), a.getOClubId());
                        continue;
                    }
                    t = a.getTitle();
                    obj.put("oClubUrl", systemConfig.getBrandClubRoot() + "/" + oClub.getUrl());
                } else if (i.getType() == DynaInfo.TYPE_PICTURE) {
                    Album a = albumService.getAlbumById(i.getTargetId());
                    User u = userService.findUser(i.getCreateBy());
                    t = u.getNickname() + "上传了" + i.getPictureNum() + "张相片到《" + a.getName() + "》";
                } else if (i.getType() == DynaInfo.TYPE_COMMENT) {
                    if (StringUtils.isBlank(i.getContent())) {
                        User u = userService.findUser(i.getCreateBy());
                        t = u.getNickname() + "发表了一条说说";
                    } else {
                        t = i.getContent();
                        t = dynaService.updateDynaContentByImages(i.getDynaInfoId(), t);
                    }
                } else if (i.getType() == DynaInfo.TYPE_VOTE) {
                    Vote vote = voteService.findVoteByVoteId(i.getTargetId());
                    t = vote.getVoteTitle();
                } else if (i.getType() == DynaInfo.TYPE_NOTICE) {
                    t = i.getContent();
                }
                t = WebUtils.transformNoFilterPictureThenLimit(t, 23);//置顶的地方最多显示23个表情的宽度+...

                if (i.getType() == DynaInfo.TYPE_CREATE_CLUB) {
                    t = "车友会主页：" + systemConfig.getRoot() + "/" + club.getClubUrl() + "/，大家快去邀请车友加入吧！";
                } else if (i.getType() == DynaInfo.TYPE_JOIN_CLUB) {
                    t = "我已经加入了" + club.getName() + "，现在我是一个有组织的人了！";
                }


                i.setTitle(t);
                obj.put("dynaInfoId", i.getDynaInfoId());
                obj.put("userId",i.getCreateBy());
                obj.put("typeDesc", i.getTypeDesc());
                obj.put("type", i.getType());
                obj.put("title", i.getTitle());
                obj.put("targetId", i.getTargetId());
                arr.add(obj);
            }
        }
        JSONObject rs = new JSONObject();
        rs.put("list", arr);
        printSuccessMsg(response, "", rs, callback);
    }

    /**
     *
     * 动态置顶
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/top.do", method = RequestMethod.POST)
    public void top(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = null;
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        if (clubId == 0 || dynaInfoId == 0) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法请求参数", callback);
            return;
        }
        //权限判断
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            printErrorMsg(response, AppUtils.STATUS_NOLOGIN_ERROR, "您还没有登陆", callback);
            return;
        }
        ClubMember m = memberService.findClubMemberByUserId(user.getUid());
        if (m == null || !m.isAdministrator()) {
            printErrorMsg(response, AppUtils.STATUS_PERMISSIONS_ERROR, "没有权限", callback);
            return;
        }
        if (dynaService.getTopCount(clubId) >= MAX_TOP_COUNT) {
            printErrorMsg(response, AppUtils.STATUS_PERMISSIONS_ERROR, "置顶最多只能显示5条，请先删除！", callback);
            return;
        }
        boolean isSuccess = dynaService.doTop(dynaInfoId, clubId);
        if (isSuccess) {
            printErrorMsg(response, AppUtils.STATUS_OK, "置顶成功", callback);
        } else {
            printErrorMsg(response, AppUtils.STATUS_FAIL, "置顶失败", callback);
        }
    }

    /**
     *
     * 取消置顶
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/cancelTop.do", method = RequestMethod.POST)
    public void cancelTop(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = null;
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        if (clubId == 0 || dynaInfoId == 0) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法请求参数", callback);
            return;
        }
        //权限判断
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            printErrorMsg(response, AppUtils.STATUS_NOLOGIN_ERROR, "您还没有登陆", callback);
            return;
        }
        ClubMember m = memberService.findClubMemberByUserId(user.getUid());
        if (m == null || !m.isAdministrator()) {
            printErrorMsg(response, AppUtils.STATUS_PERMISSIONS_ERROR, "没有权限", callback);
            return;
        }
        boolean isSuccess = dynaService.cancelTop(dynaInfoId, clubId);
        if (isSuccess) {
            printErrorMsg(response, AppUtils.STATUS_OK, "删除成功", callback);
        } else {
            printErrorMsg(response, AppUtils.STATUS_FAIL, "删除失败", callback);
        }
    }

    /**
     *
     * 会长或副会长删除车友会动态
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/deleteDyna.do", method = RequestMethod.POST)
    //TODO 车友会首页删除动态（只删除车友会首页的动态）
    public void deleteDyna(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = null;
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        if (clubId == 0 || dynaInfoId == 0) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法请求参数", callback);
            return;
        }
        //权限判断
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            printErrorMsg(response, AppUtils.STATUS_NOLOGIN_ERROR, "您还没有登陆", callback);
            return;
        }
        boolean isSuccess;
        ClubDyna clubDyna = dynaService.findClubDynaById(dynaInfoId, clubId);
        DynaInfo info = null;
        if (clubDyna != null) {
            info = dynaService.findDynaInfoById(clubDyna.getDynaInfoId(), clubDyna.getCreateDate());
        }
        ClubMember m = memberService.findMember(user.getUid(), clubId);
        if ((m != null && m.isAdministrator()) || info.getCreateBy() == user.getUid()) {
        } else {
            printErrorMsg(response, AppUtils.STATUS_PERMISSIONS_ERROR, "没有权限", callback);
            return;
        }
        
        if(info == null) {
        	 printErrorMsg(response, AppUtils.STATUS_FAIL, "动态不存在", callback);
             return;
        }
        
        if (info.getType() == DynaInfo.TYPE_ACTIVITY) {//会长或副会长删除活动时，同时删除终端活动
            activityService.removeActivity(info.getTargetId());//删除活动
            dynaService.deleteUserDyna(info.getCreateBy(), dynaInfoId);
            dynaService.deleteCityDyna(info.getDynaInfoId(), info.getProvinceId(), info.getCityId());
            dynaIndexService.deleteDynaIndex(info.getDynaInfoId());  // 删除动态索引
        } 
        if (info.getType() == DynaInfo.TYPE_VOTE) {//投票动态
            voteService.deleteVote(info.getTargetId());
            dynaService.deleteUserDyna(info.getCreateBy(), dynaInfoId);
            dynaService.deleteCityDyna(info.getDynaInfoId(), info.getProvinceId(), info.getCityId());
            dynaIndexService.deleteDynaIndex(info.getDynaInfoId());
        }
        
        
        isSuccess = dynaService.deleteClubDyna(info.getClubId(), dynaInfoId) > 0;    
        if (isSuccess) {
            if (((clubDyna.getType() == DynaInfo.TYPE_TOPIC)
                    || (clubDyna.getType() == DynaInfo.TYPE_QUESTION))
                    && info != null) {
                //帖子被会长删除，通知用户
                messageService.send(userService.findUser(info.getCreateBy()), MessageService.DELETE_TOPIC,
                        info.getTitle(), messageService.assembleUserUrl(user.getUid(), user.getNickname()), user.getNickname());
            }
            //说说被会长删除，通知用户
            if (clubDyna.getType() == DynaInfo.TYPE_COMMENT) {
                messageService.send(userService.findUser(info.getCreateBy()), MessageService.DELETE_COMMENT,
                        messageService.assembleUserUrl(user.getUid(), user.getNickname()), user.getNickname());
            }
            printErrorMsg(response, AppUtils.STATUS_OK, "删除成功", callback);
        } else {
            printErrorMsg(response, AppUtils.STATUS_FAIL, "删除失败", callback);
        }
    }

    /**
     *
     * 删除车友会动态
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/deleteUserDyna.do", method = RequestMethod.POST)
    public void deleteUserDyna(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = null;
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        if (clubId == 0 || dynaInfoId == 0) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法请求参数", callback);
            return;
        }
        //权限判断
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            printErrorMsg(response, AppUtils.STATUS_NOLOGIN_ERROR, "您还没有登陆", callback);
        } else {
            dynaService.deleteUserDyna(user.getUid(), dynaInfoId);//删除用户动态
            dynaService.deleteClubDyna(clubId, dynaInfoId);//同时删除车友会动态
            dynaIndexService.deleteDynaIndex( dynaInfoId );//删除动态索引
            printErrorMsg(response, AppUtils.STATUS_OK, "删除成功", callback);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getReplyListByDynaInfoId.do", method = RequestMethod.GET)
    public void getReplyListByDynaInfoId(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        Pager<DynaReply> dynaPager = dynaService.getReplyListByDynaInfoId(dynaInfoId, 1, 10);
        JSONObject rs = new JSONObject();
        rs.put("replyCount", dynaPager.getTotal());
        JSONArray arr = new JSONArray();
        for (DynaReply d : dynaPager.getResultList()) {
            JSONObject obj = new JSONObject();
            obj.put("niceTime", DateUtils.getFormatedTime(d.getCreateDate()));
            obj.put("dynaReplyId", d.getDynaReplyId());
            obj.put("dynaInfoId", d.getDynaInfoId());
            obj.put("userId", d.getCreateBy());
            obj.put("userAvatar", WebUtils.face(d.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
            obj.put("nickName", d.getCreateName());
            obj.put("content", EncodeUtils.encodeForHTML(d.getContent()));
            obj.put("postId", d.getPostId());
            obj.put("postToUserId", d.getPostToUserId());
            obj.put("postToUserAvatar", WebUtils.face(d.getPostToUserId(), DEFAULT_AUTHORPHOTO_SIZE));
            obj.put("postToNickName", d.getPostToNickName());
            obj.put("postTo", d.getPostToPostId());
            obj.put("postToDynaReplyId", d.getPostToDynaReplyId());
            obj.put("postToPostId", d.getPostToPostId());
            arr.add(obj);
        }
        rs.put("replyList", arr);
        printSuccessMsg(response, "", rs, null);
    }

    @ResponseBody
    @RequestMapping(value = "/getDynaListByClubId.do", method = RequestMethod.GET)
    public void getDynaListByClubId(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", 10, 5, 20);
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        int xssEncode = WebUtils.paramInt(request, "xssEncode", 2);
        int needToViewUrl = WebUtils.paramInt(request, "needToViewUrl", 0);
        Pager<DynaInfo> dynaPager = dynaService.getDynaListByClubId(clubId, pageNo, pageSize);
        dynaService.filterImages(dynaPager);
        JSONArray list = new JSONArray();
        if (dynaPager != null) {
            for (DynaInfo i : dynaPager.getResultList()) {
                String templateId = "";
                JSONObject obj = new JSONObject();
                if (needToViewUrl == 1) {
                    obj.put("content", WebUtils.dynaSubjectContent(systemConfig.getRoot(), WebUtils.transformToBBSFace(CommentDynaUtils.appendUrlUBB(i.getContent())), i.getSubjectIds()));
                } else {
                    obj.put("content", WebUtils.transformToBBSFace(i.getContent()));
                }

                if (i.getType() == DynaInfo.TYPE_ACTIVITY) {
                    Activity a = activityService.findById(i.getTargetId());
                    if (a == null) {
                        log.error("dirty data,targetId not correct :[dynaInfo:{}],[clubId:{}],[targetId(activityId):{}]", i.getDynaInfoId(), i.getClubId(), i.getTargetId());
                        continue;
                    }
                    obj.put("activityId", i.getTargetId());
                    obj.put("activityCover", a.getUrl160x107());
                    obj.put("activityTitle", a.getTitle());
                    obj.put("activityStartTime", DateUtils.format(a.getBeginDate()));
                    obj.put("activityEndTime", DateUtils.format(a.getEndDate()));
                    obj.put("activityExpiredTime", DateUtils.format(a.getSignupDate(), "yyyy-MM-dd HH:mm:ss"));
                    obj.put("activityPlace", a.getProvinceId() == 0 ? "线上" : a.getProvinceName() + a.getCityName());
                    obj.put("activityMoney", a.getMoney());
                    obj.put("activityMaxJoin", a.getMaxJoin());
                    templateId = "template-activityDyna";
                } else if (i.getType() == DynaInfo.TYPE_JOIN_ACTIVITY) {
                    OActivity a = oActivityService.findValidActivity(i.getTargetId());
                    if (a == null) {
                        log.error("oActivity! dirty data,targetId not correct :[dynaInfo:{}],[clubId:{}],[targetId(activityId):{}]", i.getDynaInfoId(), i.getClubId(), i.getTargetId());
                        continue;
                    }
                    OClub oClub = oClubService.findValidClub(a.getOClubId());
                    if (oClub == null) {
                        log.error("oClub! dirty data,oClubId not correct :[dynaInfo:{}],[clubId:{}],[oClubId:{}]", i.getDynaInfoId(), i.getClubId(), a.getOClubId());
                        continue;
                    }
                    obj.put("oClubUrl", systemConfig.getBrandClubRoot() + "/" + oClub.getUrl());
                    obj.put("oClubName", oClub.getName());
                    obj.put("activityId", i.getTargetId());
                    obj.put("activityCover", a.getPicUrl160x120());
                    obj.put("activityTitle", a.getTitle());
                    obj.put("activityStartTime", DateUtils.format(a.getBeginDate()));
                    obj.put("activityEndTime", DateUtils.format(a.getEndDate()));
                    obj.put("activityExpiredTime", DateUtils.format(a.getSignupDate(), "yyyy-MM-dd HH:mm:ss"));
                    obj.put("activityPlace", a.getProvinceId() == 0 ? "线上" : a.getProvinceName() + a.getCityName());
                    obj.put("activityMoney", a.getMoney());
                    obj.put("activityMaxJoin", a.getMaxJoin());
                    templateId = "template-joinActivityDyna";
                } else if (i.getType() == DynaInfo.TYPE_PICTURE) {
                    Album a = albumService.getAlbumById(i.getTargetId());
                    if (a == null) {
                        log.error("dirty data,targetId not correct :[dynaInfo:{}],[clubId:{}],[targetId(albumId):{}]", i.getDynaInfoId(), i.getClubId(), i.getTargetId());
                        continue;
                    }
                    templateId = "template-pictureDyna";
                    obj.put("albumId", a.getAlbumId());
                    obj.put("albumName", a.getName());
                    obj.put("pictureNum", i.getPictureNum());
                } else if (i.getType() == DynaInfo.TYPE_CREATE_CLUB) {
                    templateId = "template-createClubDyna";
                } else if (i.getType() == DynaInfo.TYPE_JOIN_CLUB) {
                    templateId = "template-joinClubDyna";
                } else if (i.getType() == DynaInfo.TYPE_COMMENT) {
                    if (!StringUtils.isBlank(i.getSubjectIds())) {
                        templateId = "template-subjectDyna";
                        obj.put("subjectCount", subjectDynaService.countSubjectDyna(i.getSubjectIds()));
                    } else {
                        templateId = "template-commentDyna";
                    }
                } else if (i.getType() == DynaInfo.TYPE_NOTICE) {
                    templateId = "template-noticeDyna";
                    obj.put("noticeId", i.getClubId());
                } else if (i.getType() == DynaInfo.TYPE_QUESTION || i.getType() == DynaInfo.TYPE_TOPIC) {
                    obj.put("topicId", i.getTargetId());
                    obj.put("forumId", i.getForumId());
                    templateId = "template-topicDyna";
                    obj.put("title", EncodeUtils.encodeForHTML(i.getTitle(), xssEncode));
                    obj.put("content", WebUtils.transformNoBBSFaceThenLimit(i.getContent(), 120, xssEncode));
                    obj.put("isPick", i.getPick());
                    obj.put("petrol", i.getPetrol());
                    obj.put("isRecommend", i.getRecommend());
                } else if (i.getType() == DynaInfo.TYPE_VOTE) {
                    Vote vote = voteService.findVoteByVoteId(i.getTargetId());
                    if (vote == null) {
                        log.error("dirty data,targetId not correct :[dynaInfo:{}],[clubId:{}],[targetId(voteId):{}]", i.getDynaInfoId(), i.getClubId(), i.getTargetId());
                        continue;
                    }
                    templateId = "template-voteDyna";
                    obj.put("voteId", vote.getVoteId());
                    obj.put("voteTitle", vote.getVoteTitle());
                    obj.put("voteCount", vote.getVoteCount());
                    String clubUrl = "";
                    Club club = clubService.getClub(clubId);
                    if (club != null) {
                        clubUrl = club.getClubUrl();
                    }
                    obj.put("dynaDetailUrl", systemConfig.getRoot() + "/" + clubUrl + "/dt/" + i.getDynaInfoId() + "/");
                }
                obj.put("type", i.getType());
                obj.put("templateId", templateId);
                obj.put("avatar", WebUtils.face(i.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
                obj.put("nickName", EncodeUtils.encodeForHTML(userService.findUser(i.getCreateBy()).getNickname(), xssEncode));
                obj.put("userId", i.getCreateBy());
                obj.put("dynaInfoId", i.getDynaInfoId());
                obj.put("year", DateUtils.format(i.getCreateDate(), "yyyy"));
                obj.put("createDate", DateUtils.format(i.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                obj.put("fmtCreateDate", DateUtils.format(i.getCreateDate(), "MM-dd HH:mm:ss"));
                obj.put("praiseCount", i.getPraiseCount());
                obj.put("postCount", i.getPostCount());
                obj.put("fromType", i.getFromType());
                JSONArray array = new JSONArray();
                for (DynaImage img : i.getImages()) {
                    JSONObject o = img.toJSONObject();
                    String url;
                    if (i.getImages().size() > 1) {
                        url = img.getUrl120x80();
                    } else {
                        url = (img.getUrl240x160());
                    }
                    o.put("url", url);
                    array.add(o);
                }
                obj.put("images", array);
                list.add(obj);
            }
        }
        JSONObject obj = new JSONObject();
        obj.put("list", list);
        printSuccessMsg(response, "", obj, null);
    }

    @ResponseBody
    @RequestMapping(value = "/getPraiseList.do", method = RequestMethod.GET)
    public void getPraiseList(HttpServletRequest request, HttpServletResponse response) {
        User user = userAuth.getUser(request, response);//验证用户是否登录
        if (user == null || user.getUid() == 0) {
            printErrorMsg(response, AppUtils.STATUS_NOLOGIN_ERROR, "您还没有登陆", null);
            return;
        }
        String[] idsStr = WebUtils.param(request, "dynaInfoIds", "").split(",");
        List<Long> ids = new ArrayList<Long>();
        for (String id : idsStr) {
            try {
                ids.add(Long.parseLong(id));
            } catch (NumberFormatException e) {
                continue;
            }
        }
        JSONArray arr = new JSONArray();
        if (!ids.isEmpty()) {
            List<DynaPraise> list = dynaService.listDynaPraise(user.getUid(), ids);
            for (DynaPraise dp : list) {
                JSONObject o = new JSONObject();
                o.put("dynaInfoId", dp.getDynainfoId());
                arr.add(o);
            }
        }
        JSONObject rs = new JSONObject();
        rs.put("list", arr);
        printSuccessMsg(response, "已点赞列表", rs, null);
    }

    @ResponseBody
    @RequestMapping(value = "/doPraise.do", method = RequestMethod.POST)
    public void doPraise(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            printErrorMsg(response, AppUtils.STATUS_NOLOGIN_ERROR, "您还没有登陆", null);
            return;
        }
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0);
        Date createDate = WebUtils.parseDate(request, "createDate");
        int isPraise = WebUtils.paramInt(request, "isPraise", -1);
        if (isPraise == -1 || createDate == null || dynaInfoId == 0) {
            printErrorMsg(response, "参数出错！", null);
            return;
        }
        if (isPraise == 1) {
            dynaService.doPraise(user.getUid(), dynaInfoId, createDate, DynaPraise.STATUS_PRAISE);
        } else {
            dynaService.doPraise(user.getUid(), dynaInfoId, createDate, DynaPraise.STATUS_UNPRAISE);
        }
        printSuccessMsg(response, "操作成功", null, null);
    }

    @ResponseBody
    @RequestMapping(value = "/getPraiseUserList.do", method = RequestMethod.GET)
    public void getPraiseUserList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", DEFAULT_PRAISE_PAGE_SIZE, 1, 50);
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0);
        if (dynaInfoId == 0) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "参数出错！", null);
        }
        //获取点赞用户第一页列表
        Pager<User> praisePager = null;
        try {
            praisePager = dynaService.getPraiseUserList(dynaInfoId, pageNo, pageSize);
        } catch (Pager.IllegalPageException e) {
        }
        JSONObject rs = new JSONObject();
        JSONArray arr = new JSONArray();
        if (praisePager != null) {
            for (User u : praisePager.getResultList()) {
                JSONObject o = new JSONObject();
                o.put("uid", u.getUid());
                o.put("nickname", u.getNickname());
                arr.add(o);
            }
        }
        rs.put("list", arr);
        printSuccessMsg(response, "点赞用户列表", rs, null);
    }

    /**
     * 帖子精华列表页
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/listPick.do", method = RequestMethod.GET)
    public String listPick(HttpServletRequest request, HttpServletResponse response) {
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", 25, 1, MAX_PAGE_SIZE);
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        int order = WebUtils.paramInt(request, "order", 0);
        Club club = clubService.getValidClub(clubId);
        if (club == null || pageNo < 1) {
            try {
                response.sendError(404);
            } catch (Exception ex) {
                log.error("list topics fail!", ex);
            }
            return "/template/common/notFoundPage";
        }
        User user = userAuth.getUser(request, response);
        Pager<DynaInfo> pager;
        List<Bread> breadList = new ArrayList<Bread>(2);
        pager = dynaService.getPickTopicDynaListByClubId(clubId, pageNo, pageSize, order);
        //过滤掉不合法的图片
        pager = dynaService.filterImages(pager);
        if (pager == null) {
            pager = Pager.buildEmptyPager();
        }
        boolean isClubUser = false;
        ClubMember clubMember = memberService.findMember(user.getUid(), clubId);
        if (clubMember != null && clubMember.getId() > 0) {
            isClubUser = true;
        }
        List<ClubForum> clubForums = clubService.getForumList(club.getClubId());
        request.setAttribute("clubForums", clubForums);
        WebUtils.checkPageMaxNo(response, pageNo, pager.getPageCount());
        ClubController.setClubStyle(request, club.getClubId());
        request.setAttribute("isClubUser", isClubUser);
        request.setAttribute("order", order);
        request.setAttribute("clubId", clubId);
        request.setAttribute("pager", pager);
        request.setAttribute("user", user);
        request.setAttribute("breadList", breadList);
        request.setAttribute("club", club);
        return "/template/dyna/pick_list";
    }
}
